import pygame as pg
import sys,os,pickle

class MapCreator:
    def __init__(self):
        self.screen = pg.display.get_surface()
        self.Clock = pg.time.Clock()
        self.pallet = SHEET
        self.cell_size = (32,32)
        self.pal_rect = self.pallet.get_rect()
        self.map_rect = pg.Rect(288,0,544,544)
        self.map_dict = {}
        self.cells = rip_from_sheet(SHEET,self.cell_size,(8,2))
        self.selected = (0,0)
        self.done = False

    def save_map(self):
        with open("mymap.txt","wb") as myfile:
            pickle.dump(self.map_dict,myfile)
            print("Map saved.")

    def load_map(self):
        with open("mymap.txt","rb") as myfile:
            self.map_dict = pickle.load(myfile)
            print("Map loaded.")

    def change_selected(self,mouse):
        if self.pal_rect.collidepoint(mouse):
            self.selected = mouse[0]/32,mouse[1]/32

    def event_loop(self):
        keys = pg.key.get_pressed()
        for event in pg.event.get():
            if event.type == pg.QUIT or keys[pg.K_ESCAPE]:
                self.done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                mouse = pg.mouse.get_pos()
                self.change_selected(mouse)
                self.add_and_del(mouse,event)
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_s:
                    self.save_map()
                elif event.key == pg.K_l:
                    self.load_map()

    def redraw_pallet(self):
        self.screen.blit(self.pallet,(0,0))
        rect = (self.selected[0]*32,self.selected[1]*32,32,32)
        pg.draw.rect(self.screen,(255,0,0),rect,1)

    def add_and_del(self,mouse,event):
        coords = (mouse[0]-self.map_rect.x)//32,(mouse[1]-self.map_rect.y)/32
        if self.map_rect.collidepoint(mouse):
            if event.button == 1:
                self.add_tile(coords)
            elif event.button == 3:
                self.del_tile(coords)

    def del_tile(self,coords):
        if coords in self.map_dict:
            self.map_dict.pop(coords)
    def add_tile(self,coords):
        self.map_dict[coords] = self.selected

    def redraw_map(self):
        for destin,target in self.map_dict.items():
            destin = (destin[0]*32+self.map_rect.x,destin[1]*32+self.map_rect.y)
            self.screen.blit(self.cells[target],destin)

    def main(self):
        while not self.done:
            self.event_loop()
            self.screen.fill(0)
            self.screen.fill((255,255,0),(256,0,32,600))
##            self.screen.fill((0,255,0),self.map_rect)
            self.redraw_pallet()
            self.redraw_map()
            pg.display.update()
            self.Clock.tick(60)

####
def gen_height_map(cells):
    height_dict = {}
    test_mask = pg.Mask((1,cells[(0,0)].get_height()))
    test_mask.fill()
    for coord,cell in cells.items():
        heights = []
        mask = pg.mask.from_surface(cell)
        for i in range(cell.get_width()):
            height = mask.overlap_area(test_mask,(i,0))
            heights.append(height)
        height_dict[(coord)] = heights
    return height_dict

def rip_from_sheet(sheet,cell_size,sheet_size):
    coord_dict = {}
    for j in range(sheet_size[1]):
        for i in range(sheet_size[0]):
            rect = pg.Rect((i*cell_size[0],j*cell_size[1]),cell_size)
            coord_dict[(i,j)] = sheet.subsurface(rect)
    return coord_dict

if __name__ == "__main__":
    os.environ['SDL_VIDEO_CENTERED'] = '1' #Center window.
    pg.init()
    pg.display.set_mode((832,256))
    SHEET = pg.image.load("basic_tileset_big.png").convert()
    SHEET.set_colorkey((255,0,255))

    MyMap = MapCreator()
    MyMap.main()
    pg.quit();sys.exit()




